package com.invest.utils.io;

import com.invest.utils.uuid.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/7/26 Exp
 */
public class ImageBase64Utils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageBase64Utils.class);
    public static String imageToBase4(byte[] bytes){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    public static byte[] imageStrToByte(String imgStr) throws IOException {
        if (StringUtils.isBlank(imgStr))
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(imgStr);
        for(int i=0;i<b.length;++i)
        {
            if(b[i]<0)
            {
                b[i]+=256;
            }
        }
       return b;
    }

    /**
     * bootstrap的富文本插件
     * 保存image标签中的base64图片
     * 替换image标签中的uri地址改成
     * 返回替换后的内容
     * @param uriParentPath
     * @param diskParentPath
     * @param htmlBody
     * @return
     */
    public static String processBody(final String uriParentPath, final String diskParentPath,final String htmlBody) {
        StringBuilder builder = new StringBuilder(htmlBody);
        try {
            FileInfo imgInfo = getFirstImageAndReplaceUri(uriParentPath,builder);
            while (imgInfo != null && StringUtils.isNotBlank(imgInfo.getData())) {

                byte[] bytes = ImageBase64Utils.imageStrToByte(imgInfo.getData());

                String itemDiskPath = diskParentPath+imgInfo.getFullName();
                //保存文件
                OutputStream out = FileIOUtils.fileBufferedOutputStream(itemDiskPath);
                out.write(bytes);
                FileIOUtils.close(out);
                //替换地址
                imgInfo = getFirstImageAndReplaceUri(uriParentPath,builder);
            }
        }catch (Exception ex){
            LOGGER.error("替换html中image异常",ex);
        }
        return builder.toString();

    }

    public static FileInfo getFirstImageAndReplaceUri(String uriParentPath, StringBuilder htmlBody) throws UnsupportedEncodingException {


        int index = StringUtils.indexOf(htmlBody.toString(),"data:image");
        if(index>0){
            String substring = StringUtils.substring(htmlBody.toString(),index+"data:image".length()+1);
            String imageType = StringUtils.left(substring,StringUtils.indexOf(substring,";"));
            String imageData = StringUtils.substring(substring,StringUtils.indexOf(substring,",")+1,
                    StringUtils.indexOf(substring,"\""));
            FileInfo info = new FileInfo(String.valueOf(IdWorker.getFileNameWork().nextId()),
                    imageType);
            info.setData(imageData);
            int end = StringUtils.indexOf(htmlBody.toString(),imageData)+imageData.length();
            htmlBody.replace(index,end,uriParentPath+info.getFullName());
            return info;
        }
        return null;
    }


}
